//
//  WQCDetailViewController.m
//  renxinghuan
//
//  Created by 王晓民 on 2018/3/22.
//  Copyright © 2018年 吴清翠. All rights reserved.
//

#import "WQCDetailViewController.h"
#import "configuration.h"
#import "WQCDetalTableViewCell.h"
#import "WQCMakePlanViewController.h"
#import "WQCHistooryViewController.h"
#import "WQCStopViewController.h"
#import "WQCAddViewController.h"
#import "amountModel.h"
#import "myModel.h"
#import "WQCBankViewController.h"
#import "XLPasswordView.h"
#import "WQCMemberViewController.h"
@interface WQCDetailViewController ()<UITableViewDataSource,UITableViewDelegate,XLPasswordViewDelegate>
@property(nonatomic,strong)UITableView  *detalTabView;
@property(nonatomic,strong)NSMutableArray  *allPlanArr;
@property(nonatomic,strong)UIButton * backButton;
@property(nonatomic,strong)UILabel *Total;
@property(nonatomic,strong)UILabel * Totallabel;
@property(nonatomic,strong)UILabel *Statementlabel;
@property(nonatomic,strong) UILabel *Gracelabel;
@property(nonatomic,strong)  UILabel *Repaymentlabel;
@property(nonatomic,strong)NSString  *pass;
@property(nonatomic,strong)NSString  *planid;
@property(nonatomic,strong) NSString  *banktype;


@end

@implementation WQCDetailViewController
-(void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden =NO;

}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.allPlanArr = [[NSMutableArray alloc]init];

    self.view.backgroundColor = [UIColor whiteColor];
    
    [self setupNav];
    UIView  *bgView = [MyUIClass makeUIViewWithFram:CGRectMake(0, NavHeight, kScreenW, 200) andBackColor:wycMain];
    //白色
    UIImageView * backView2 = [[UIImageView alloc] init];
    backView2.frame = CGRectMake(10, 20, ScreenWidth-20, 170);
    backView2.layer.cornerRadius = 30 * px;
    backView2.backgroundColor = [UIColor whiteColor];
    [bgView addSubview:backView2];
    
   
    UILabel *benqizhangdan = [[UILabel alloc] init];
    benqizhangdan.frame = CGRectMake(15, 15, ScreenWidth-60, 30);
    benqizhangdan.text =@"实际还款金额";
    benqizhangdan.textAlignment = NSTextAlignmentLeft;
    benqizhangdan.textColor = [UIColor blackColor];
    benqizhangdan.font = [UIFont systemFontOfSize:17];
    [backView2 addSubview:benqizhangdan];
    _Total= [[UILabel alloc] init];
    _Total.frame = CGRectMake(ScreenWidth-130, benqizhangdan.y, 100, 30);
    _Total.textAlignment = NSTextAlignmentLeft;
    _Total.textColor = wycMain;
    _Total.text = @"暂无计划";
    _Total.font = [UIFont systemFontOfSize:15];
    [backView2 addSubview:_Total];
    
    //总额度
   _Totallabel = [[UILabel alloc] init];
    _Totallabel.frame = CGRectMake(15, 60, 200, 30);
    _Totallabel.textAlignment = NSTextAlignmentLeft;
    _Totallabel.text = @"0.00";
    _Totallabel.textColor = [UIColor blackColor];
    _Totallabel.font = [UIFont boldSystemFontOfSize:25];
    [backView2 addSubview:_Totallabel];
    
 
    //卡内余额
     _Statementlabel= [[UILabel alloc] init];
    _Statementlabel.frame = CGRectMake(0, benqizhangdan.frame.size.height+benqizhangdan.frame.origin.y+70, backView2.width / 3, 50 * px);
    _Statementlabel.textAlignment = NSTextAlignmentCenter;
    _Statementlabel.text = @"--";
    _Statementlabel.textColor = [UIColor blackColor];
    _Statementlabel.font = [UIFont boldSystemFontOfSize:15];
    [backView2 addSubview:_Statementlabel];
    
    
    UILabel *Statement = [[UILabel alloc] init];
    Statement.frame = CGRectMake(_Statementlabel.x, CGRectGetMaxY(_Statementlabel.frame)+10 , _Statementlabel.width, _Statementlabel.height);
    Statement.text = @"计划本金";
    Statement.textAlignment = NSTextAlignmentCenter;
    Statement.textColor = [UIColor lightGrayColor];
    Statement.font = [UIFont systemFontOfSize:15];
    [backView2 addSubview:Statement];
    
    //计划配置
    _Repaymentlabel= [[UILabel alloc] init];
    _Repaymentlabel.frame = CGRectMake(backView2.width / 3, _Statementlabel.y, _Statementlabel.width, _Statementlabel.height);
    _Repaymentlabel.text = @"--";
    _Repaymentlabel.textAlignment = NSTextAlignmentCenter;
    _Repaymentlabel.textColor = [UIColor blackColor];
    _Repaymentlabel.font = [UIFont boldSystemFontOfSize:15];
    [backView2 addSubview:_Repaymentlabel];
    
    
    UILabel *Repayment = [[UILabel alloc] init];
    Repayment.frame = CGRectMake(_Repaymentlabel.x, CGRectGetMaxY(_Repaymentlabel.frame)+10, _Statementlabel.width, _Statementlabel.height);
    Repayment.text = @"计划配置";
    Repayment.textColor = [UIColor lightGrayColor];
    Repayment.textAlignment = NSTextAlignmentCenter;
    Repayment.font = [UIFont systemFontOfSize:15];
    [backView2 addSubview:Repayment];
    
    
    
   _Gracelabel = [[UILabel alloc] init];
    _Gracelabel.frame = CGRectMake((backView2.width /3)*2, _Statementlabel.y, _Statementlabel.width, _Statementlabel.height);
    _Gracelabel.text = @"--";
    _Gracelabel.textAlignment = NSTextAlignmentCenter;
    _Gracelabel.textColor = [UIColor blackColor];
    _Gracelabel.font = [UIFont boldSystemFontOfSize:15];
    [backView2 addSubview:_Gracelabel];
    
    
    UILabel *Grace = [[UILabel alloc] init];
    Grace.frame = CGRectMake(_Gracelabel.x, CGRectGetMaxY(_Gracelabel.frame)+10, _Statementlabel.width, _Statementlabel.height);
    Grace.text = @"总手续费";
    Grace.textColor = [UIColor lightGrayColor];
    Grace.textAlignment = NSTextAlignmentCenter;
    Grace.font = [UIFont systemFontOfSize:15];
    [backView2 addSubview:Grace];
    [self loadAllPlan];
    self.detalTabView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH) style:UITableViewStyleGrouped];
    self.detalTabView.dataSource = self;
    self.detalTabView.delegate = self;
    self.detalTabView.tableHeaderView = bgView;
    self.detalTabView.sectionFooterHeight = 10;
    self.detalTabView.sectionHeaderHeight = 10;
    [self.view addSubview:self.detalTabView];
    
     _backButton = [[UIButton alloc] init];
    _backButton.frame = CGRectMake(kScreenW/2-210*px, kScreenH-120,  420 * px, 150 * px);
    [_backButton addTarget:self action:@selector(makeButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [_backButton setTitle:@"创建计划" forState:UIControlStateNormal];
    _backButton.titleLabel.font = [UIFont systemFontOfSize:BigFont];
    [_backButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _backButton.layer.cornerRadius = 75 * px;
    _backButton.backgroundColor = wycMain;
    [self.view addSubview:_backButton];

    
}
- (void)addView{
    UILabel * showlabel = [[UILabel alloc] init];
    showlabel.text = @"暂无还款计划";
    showlabel.textAlignment = NSTextAlignmentCenter;
    showlabel.frame = CGRectMake(0, 350, ScreenWidth, 60* px);
    showlabel.textColor = [UIColor lightGrayColor];
    showlabel.font = [UIFont systemFontOfSize:SmallFont];
    [self.view addSubview:showlabel];
    
}
#pragma mark    -   XLPasswordViewDelegate

/**
 *  输入密码位数已满时调用
 */
- (void)passwordView:(XLPasswordView *)passwordView didFinishInput:(NSString *)password
{
    NSLog(@"输入密码位数已满,在这里做一些事情,例如自动校验密码%@",password);
    
    [self loadStop:password];
    
}
//创建计划
-(void)makeButtonClick
{
   
    
    [HttpTool POST:getUserVip params:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        
        NSLog(@"计划%@",responseObject);
        if ([[responseObject objectForKey:@"code"] intValue] == 0)
        {
            WQCMakePlanViewController  *makeView = [[WQCMakePlanViewController alloc]init];
            makeView.billStr = self.billStr;
            makeView.amountStr = self.amountStr;
            makeView.lastnumberStr = self.lastnumberStr;
            makeView.borowStr = self.borowStr;
            makeView.banknameStr =self.nameStr;
            makeView.bankidStr = self.bankIdStr;
            makeView.cardIdStr = self.cardidStr;
            [self.navigationController pushViewController:makeView animated:YES];
            
        }
        else
        {
            WQCMemberViewController  *vipView = [[WQCMemberViewController alloc]init];
            [self.navigationController pushViewController:vipView animated:YES];

        }
        
    } fail:^(NSURLSessionDataTask *task, NSError *error) {
        
        [SVProgressHUD showImage:nil status:Failed];
      
    }];
  
}
- (void)setupNav {
    
    [self.navigationController.navigationBar setBarTintColor:wycMain];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
    NSString * titleStr = [NSString stringWithFormat:@"%@(%@)",self.nameStr,self.lastnumberStr];
    self.navigationItem.title = titleStr;
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithImage:@"Three" hight:@"Three" target:self action:@selector(ThreeClick)];

}
-(void)ThreeClick
{
    UIAlertController *actionSheetController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *stopInfoAction = [UIAlertAction actionWithTitle:@"终止当前计划" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        
        if ([self.banktype isEqualToString:@"1"]||[self.banktype isEqualToString:@"2"]){
            if ([[WYCAccountTool unarchivehavePayPassword] isEqualToString:@"1"])
            {
                //未设置支付密码
                WQCBankViewController  *codeView = [[WQCBankViewController alloc]init];
                [self.navigationController pushViewController:codeView animated:YES];
            }
            else
            {
                XLPasswordView *passwordView = [XLPasswordView passwordViewWithKeyboardType:XLPasswordViewKeyboardTypeSystem];
                passwordView.delegate = self;
                [passwordView showPasswordInView:self.view];
                [passwordView.passwordInputView.textField becomeFirstResponder];

            }
        }
        
    }];
    UIAlertAction *showAllInfoAction = [UIAlertAction actionWithTitle:@"查看往期计划" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        WQCHistooryViewController  *history = [[WQCHistooryViewController alloc]init];
        history.bankName = self.nameStr;
        history.lastNumber =self.lastnumberStr;
        history.cardid =self.cardidStr;
        [self.navigationController pushViewController:history animated:YES];
        
    }];
    
    UIAlertAction *pickAction = [UIAlertAction actionWithTitle:@"编辑信用卡" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        if (![self.banktype isEqualToString:@"1"]||[self.banktype isEqualToString:@"2"])
        {
            WQCAddViewController  *addview =[[WQCAddViewController alloc]init];
            addview.myFlag = @"777";
            addview.nameStr = self.nameStr;
            addview.lastnum = self.lastnumberStr;
            addview.billDay = self.billStr;
            addview.dueDateStr = self.dueDateStr;
            addview.mobileStr = self.mobileStr;
            addview.cardNumberStr = self.cardNumberStr;
            addview.cvn2str= self.cvn2Str;
            addview.validityStr =self.validityStr;
            addview.amontStr =self.amountStr;
            addview.bankidStr =self.bankIdStr;
            addview.cardidStr =self.cardidStr;
            
            [self.navigationController pushViewController:addview animated:YES];
        }
        else
        {
            [SVProgressHUD showImage:nil status:@"计划执行中无法编辑信用卡信息"];
            [SVProgressHUD setDefaultStyle:SVProgressHUDStyleCustom];
            [SVProgressHUD setForegroundColor:[UIColor whiteColor]]; //字体颜色
            [SVProgressHUD setBackgroundColor:[UIColor blackColor]];   //背景颜色
        }
        
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [actionSheetController addAction:stopInfoAction];
    [actionSheetController addAction:showAllInfoAction];
    [actionSheetController addAction:pickAction];
    [actionSheetController addAction:cancelAction];
    
    
    [self presentViewController:actionSheetController animated:YES completion:nil];
}
-(void)loadStop:(NSString *)pass
{
    NSLog(@"终止%@",self.planid);
    //RSA密码加密
    NSString *pas = [RSA encryptString:pass publicKey:RSA_P_KEY];
    
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    params[@"planId"] = self.planid;
    params[@"payPassword"]=pas;
    params[@"cardId"] = self.cardidStr;

    [HttpTool POST:stopPlan params:params success:^(NSURLSessionDataTask *task, id responseObject) {
        
        NSLog(@"终止计划%@",responseObject);
        if ([[responseObject objectForKey:@"code"] intValue] == 0)
        {
            [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"终止计划成功"];
            [SVProgressHUD setDefaultStyle:SVProgressHUDStyleCustom];
            [SVProgressHUD setForegroundColor:[UIColor whiteColor]]; //字体颜色
            [SVProgressHUD setBackgroundColor:[UIColor blackColor]];   //背景颜色

        }
        else
        {
            [SVProgressHUD showImage:[UIImage imageNamed:@""] status:[responseObject objectForKey:@"message"]];
            [SVProgressHUD setDefaultStyle:SVProgressHUDStyleCustom];
            [SVProgressHUD setForegroundColor:[UIColor whiteColor]]; //字体颜色
            [SVProgressHUD setBackgroundColor:[UIColor blackColor]];   //背景颜色

        }
        [self.navigationController popViewControllerAnimated:YES];

    } fail:^(NSURLSessionDataTask *task, NSError *error) {
        
        [SVProgressHUD showImage:nil status:Failed];
        [SVProgressHUD setDefaultStyle:SVProgressHUDStyleCustom];
        [SVProgressHUD setForegroundColor:[UIColor whiteColor]]; //字体颜色
        [SVProgressHUD setBackgroundColor:[UIColor blackColor]];   //背景颜色
    }];
}

#pragma mark - TableView DataSource Method

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.allPlanArr.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 85;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    static NSString * strID = @"cell";
    
    WQCDetalTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:strID];
    
    if (cell == nil)
    {
        
        cell=[[[NSBundle mainBundle]loadNibNamed:@"WQCDetalTableViewCell" owner:self options:nil]lastObject];
        
    }
    amountModel * DetailModel = self.allPlanArr[indexPath.row];
    cell.creatTimeLb.text = DetailModel.executeTime;
    self.planid = DetailModel.planId;
    cell.poundageLb.text = [NSString stringWithFormat:@"%.2f",[DetailModel.poundage doubleValue]];
    NSString  *type = DetailModel.type;
    if ([type isEqualToString:@"1"]) {
        cell.typeLb.image = [UIImage imageNamed:@"consumption"];
        cell.amountLb.text = [NSString stringWithFormat:@"-%.1f",[DetailModel.amount doubleValue]];

    }
    else
    {
        cell.typeLb.image = [UIImage imageNamed:@"repayment"];
        cell.amountLb.text = [NSString stringWithFormat:@"+%.1f",[DetailModel.amount doubleValue]];


    }
    cell.stateLb.textColor = wycMain;

    NSString  *state = DetailModel.state;
    if ([state isEqualToString:@"1"]) {
        cell.stateLb.text = @"待执行";
        _backButton.hidden = YES;
        _Total.text = @"待执行";
        
    }
    else if ([state isEqualToString:@"2"])
    {
        cell.stateLb.text = @"执行中";
        
        _backButton.hidden = YES;
        _Total.text = @"执行中";


    }
    else if ([state isEqualToString:@"3"])
    {
        cell.stateLb.text = @"执行成功";
        _backButton.hidden = NO;
        _Total.text = @"执行成功";



    }else if ([state isEqualToString:@"4"])
    {
        cell.stateLb.text = @"执行失败";
        cell.stateLb.textColor = [UIColor redColor];
        _backButton.hidden = NO;
        _Total.text = @"执行失败";



    }
    
    else if ([state isEqualToString:@"5"])
    {
        cell.stateLb.text = @"执行失败";
        _backButton.hidden = NO;
        _Total.text = @"执行失败";
        
        _Total.textColor = [UIColor redColor];
        cell.stateLb.textColor = [UIColor redColor];
        
    }else if ([state isEqualToString:@"6"])
    {
        cell.stateLb.text = @"还款终止";
        _backButton.hidden = NO;
        _Total.text = @"还款终止";
        _Total.textColor = [UIColor redColor];
        cell.stateLb.textColor = [UIColor redColor];

    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}


-(void)loadAllPlan
{
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    params[@"cardId"] = self.cardidStr;
    [HttpTool POST:cardPlanDetail params:params success:^(NSURLSessionDataTask *task, id responseObject) {
        
        if ([[responseObject objectForKey:@"code"] intValue] == 0)
        {
            NSDictionary * result = responseObject[@"result"];
          
            NSLog(@"计划%@",result);
                if ([result isKindOfClass:[NSNull class]])
                    {

                        NSLog(@"没有值");
                       
            }
            else
            {
                NSDictionary  *dict = result[@"plan"];
                
                _Totallabel.text = [NSString stringWithFormat:@"%.1f",[dict[@"amount"] doubleValue]];
                _Repaymentlabel.text = [NSString stringWithFormat:@"%@天%@期", dict[@"totalConsumeNum"], dict[@"totalRepaymentNum"]];
                _Gracelabel.text = [NSString stringWithFormat:@"%.2f",[dict[@"totalCharge"] doubleValue]];
                _Statementlabel.text = [NSString stringWithFormat:@"%.1f",[dict[@"balance"] doubleValue]];
                _planid =[NSString stringWithFormat:@"%@",dict[@"planId"]];
               self.banktype =[NSString stringWithFormat:@"%@",dict[@"state"]];

                NSArray * dataArray = result[@"details"];
                for (NSDictionary * dic in dataArray) {
                    
                    amountModel * DetailModel = [amountModel mj_objectWithKeyValues:dic];
                    
                    [self.allPlanArr addObject:DetailModel];
                }
            }
        }
        if (self.allPlanArr.count == 0) {
            [self addView];
            
        }
        
        [self.detalTabView reloadData];
        
    } fail:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
